package com.seanchenxi.gwt.xmlrpc.client;

import com.seanchenxi.gwt.xmlrpc.client.impl.XmlRpcClientConfigImpl;
import com.seanchenxi.gwt.xmlrpc.client.impl.XmlRpcRequestImpl;

/**
 * A factory for creating XmlRpcObject objects.
 */
public class XmlRpcObjectFactory {

	/**
	 * Creates a new XmlRpcObject object.
	 *
	 * @param <T> the generic type
	 * @param methodName the method name
	 * @param params the params
	 * @return the xml rpc request
	 */
	public static <T> XmlRpcRequest<T> createRequest(String methodName,
			Object... params) {
		return new XmlRpcRequestImpl<T>(methodName, params);
	}

	/**
	 * Creates a new XmlRpcObject object.
	 *
	 * @param url the url
	 * @return the xml rpc client config
	 */
	public static XmlRpcClientConfig createXmlRpcClientConfig(String url) {
		if(validate(url))
			return new XmlRpcClientConfigImpl(url.trim());
		else
			return null;
	}

	/**
	 * Creates a new XmlRpcObject object.
	 *
	 * @param url the url
	 * @param username the username
	 * @param password the password
	 * @return the xml rpc client config
	 */
	public static XmlRpcClientConfig createXmlRpcClientConfig(String url,
			String username, String password) {
		if(!validate(username, password))
			return createXmlRpcClientConfig(url);
		else if(validate(url))
			return new XmlRpcClientConfigImpl(url.trim(), username.trim(), password.trim());
		else 
			return null;
	}

	/**
	 * Creates a new XmlRpcObject object.
	 *
	 * @param url the url
	 * @param username the username
	 * @param password the password
	 * @param timeout the timeout, must be > 1000
	 * @return the xml rpc client config
	 */
	public static XmlRpcClientConfig createXmlRpcClientConfig(String url,
			String username, String password, int timeout) {
		if(timeout>1000 && validate(url,username,password))
			return new XmlRpcClientConfigImpl(url.trim(), username.trim(), password.trim(), timeout);
		else if(timeout<1000 && validate(url))
			return createXmlRpcClientConfig(url.trim(), username, password);
		else
			return null;
	}
	
	/**
	 * Validate.
	 *
	 * @param params the params
	 * @return true, if successful
	 */
	static boolean validate(String... params){
		boolean validated = true;
		int i = 0;
		while(i < params.length && validated){
			String str = params[0];
			if(str==null){
				validated = false;
			}else if(str.trim().length() < 1){
					validated = false;
			}
			i++;
		}
		return validated;
	}
}
